package db

import (
	"context"
	"fmt"
	"gg_server/config"
	"sync"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

// 创建 mysql 数据库连接
var (
	// gorm实例
	mysqlDB *gorm.DB
	once    sync.Once
	// mongoDB 实例
	mongoDB   *mongo.Client
	onceMongo sync.Once
)

// 连接mysql
func CreateSQLDB() *gorm.DB {
	once.Do(func() {
		// dsn := "root:root@tcp(127.0.0.1:3306)/gg?parseTime=true&loc=Local"
		var err error
		mysqlDB, err = gorm.Open(mysql.Open(config.TConfig.MysqlUri), &gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
			},
		})
		if err != nil {
			panic(fmt.Sprintln("mysql连接失败，err:", err))
		}
	})

	return mysqlDB
}

// 连接mongoDB
func CreateMongoDB() *mongo.Database {
	onceMongo.Do(func() {
		// clientOpts := options.Client().ApplyURI("mongodb://localhost:27017/?connect=direct")
		clientOpts := options.Client().ApplyURI(config.TConfig.MongoDbUri)
		var err error
		mongoDB, err = mongo.Connect(context.TODO(), clientOpts)
		if err != nil {
			panic(fmt.Sprint("mongoDB连接失败,err:", err))
		}
	})

	return mongoDB.Database("gg")
}
